package com.ruoyi.common.utils.uuid;

import org.springframework.stereotype.Component;


/**
 * 雪花算法获取分布式ID
 *
 * @author zrj
 * @date 2021/2/15
 * @since V1.0
 **/
@Component
public class IdGeneratorSnowflake {

    /**
     * 开始时间：2020-01-01 00:00:00
     */
    private final long beginTs = 1577808000000L;

    /**
     * 机器ID所占的位数
     */
    private final long workerIdBits = 3L;

    /**
     * 数据标识id所占的位数
     */
    private final long datacenterIdBits = 7L;

    /**
     * 2^10 - 1 = 1023
     */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /**
     * 支持的最大业务标识id  2^5 - 1 = 31
     */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /**
     * 序列所占的位数
     */
    private final long sequenceBits = 12;

    /**
     * 机器ID向左移12位
     */
    private final long workerIdLeftOffset = sequenceBits;

    /**
     * 业务标识id向左移15位(12+3)
     */
    private final long datacenterIdShift =  sequenceBits+workerIdBits ;

    /**
     * 时间戳向左移17位(12+3+7)
     */
    private final long timestampLeftOffset = sequenceBits+workerIdBits +datacenterIdBits;

    /**
     * 2^12 - 1 = 4095
     */
    private final long maxSequence = -1L ^ (-1L << sequenceBits);

    /**
     *  机器ID，3位
     */
    private long workerId;

    /**
     * 业务ID，7位
     */
    private long datacenterId;

    /**
     * 毫秒内序列，12位，2^12 = 4096个数字
     */
    private long sequence = 0L;

    /**
     * 上一次生成的ID的时间戳，同一个worker中
     */
    private long lastTimestamp = -1L;

    /**
     * 构造函数
     *
     * @param workerId     机器ID
     * @param datacenterId 业务ID
     */
    public void SnowflakeIdWorker(long workerId, long datacenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("机器ID WorkerId 必须大于或等于0且小于或等于%d", maxWorkerId));
        }
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("业务ID datacenterId 必须大于或等于0且小于或等于%d", maxDatacenterId));
        }
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 获取下一个ID
     *
     * @return longID
     */
    public synchronized long nextId() {
        long ts = System.currentTimeMillis();
        if (ts < lastTimestamp) {
            throw new RuntimeException(String.format("系统时钟回退了%d毫秒", (lastTimestamp - ts)));
        }

        // 同一时间内，则计算序列号
        if (ts == lastTimestamp) {
            // 序列号溢出
            if (++sequence > maxSequence) {
                ts = tilNextMillis(lastTimestamp);
                sequence = 0L;
            }
        } else {
            // 时间戳改变，重置序列号
            sequence = 0L;
        }

        lastTimestamp = ts;
        return (ts - beginTs) << timestampLeftOffset
                | datacenterId << datacenterIdShift
                | workerId << workerIdLeftOffset
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒
     *
     * @param lastTimestamp
     * @return
     */
    private long tilNextMillis(long lastTimestamp) {
        long ts = System.currentTimeMillis();
        while (ts <= lastTimestamp) {
            ts = System.currentTimeMillis();
        }
        return ts;
    }

    /**
     * 测试id生成
     *
     * @return longID
     */
    public static void main(String[] args) {
        IdGeneratorSnowflake snowflakeIdWorker = new IdGeneratorSnowflake();
        for (int i = 0; i < 20; i++) {
            snowflakeIdWorker.SnowflakeIdWorker(1,33);
            long id = snowflakeIdWorker.nextId();
            System.out.println(id);
        }
    }

}

